﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ProcDaemon
{
    public class ConsoleManager
    {
        private static readonly int _perColumnWidth = 16;
        private static readonly int _totalColumns = 7;
        private static readonly int _stateColumns = 3;

        public static int PerColumnWidth
        {
            get
            {
                return _perColumnWidth;
            }
        }

        public static int TotalColumns
        {
            get
            {
                return _totalColumns;
            }
        }

        public static int CursorLeft
        {
            get
            {
                return Console.CursorLeft;
            }
        }

        public static int CursorTop
        {
            get
            {
                return Console.CursorTop;
            }
        }

        public static void SetConsole()
        {
            Console.CursorVisible = false;
            Console.WindowWidth = _perColumnWidth * _totalColumns;
            Console.BufferWidth = _perColumnWidth * _totalColumns;
        }

        public static void ClearAndSetCursorPosition(int cursorLeft, int cursorTop)
        {
            Console.SetCursorPosition(cursorLeft, cursorTop);
            Console.Write(new string(' ', _perColumnWidth * _stateColumns));
            Console.SetCursorPosition(cursorLeft, cursorTop);
        }

        public static void Write(string value)
        {
            Console.Write(value);
        }

        public static void Write(string format, params object[] arg)
        {
            int colomnWidth = _perColumnWidth;
            var args = arg.Select(r => PadRightEx(r.ToString(), colomnWidth)).ToArray();
            Console.Write(format, args);
        }

        public static void WriteLine()
        {
            Console.WriteLine();
        }

        public static void WriteLine(string format, params object[] arg)
        {
            int colomnWidth = _perColumnWidth;
            var args = arg.Select(r => PadRightEx(r.ToString(), colomnWidth)).ToArray();
            Console.WriteLine(format, args);
        }

        public static void WriteLine(string value, int colomnWidth, char paddingChar)
        {
            Console.WriteLine(PadRightEx(value, colomnWidth, paddingChar));
        }

        private static string PadRightEx(string str, int totalByteCount, char paddingChar = ' ')
        {
            Encoding coding = Encoding.GetEncoding("gb2312");
            int dcount = 0;
            foreach (char ch in str.ToCharArray())
            {
                if (coding.GetByteCount(ch.ToString()) == 2)
                    dcount++;
            }
            string w = str.PadRight(totalByteCount - dcount, paddingChar);
            return w;
        }
    }
}
